package com.magic.web.common.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class DateUtils {
    /** 锁对象 */
    private static final Object lockObj = new Object();

    private static Map<String, ThreadLocal<SimpleDateFormat>> sdfMap = new HashMap<String, ThreadLocal<SimpleDateFormat>>();


    private static SimpleDateFormat getSdf(final String pattern) {
        ThreadLocal<SimpleDateFormat> tl = sdfMap.get(pattern);
        // 只有Map中还没有这个pattern的sdf才会生成新的sdf并放入map
        if (tl == null) {
            synchronized (lockObj) {
                // 这里是关键,使用ThreadLocal<SimpleDateFormat>替代原来直接new SimpleDateFormat
                tl = new ThreadLocal<SimpleDateFormat>() {
                    @Override
                    protected SimpleDateFormat initialValue() {
                        return new SimpleDateFormat(pattern);
                    }
                };
                sdfMap.put(pattern, tl);
            }
        }
        return tl.get();
    }

    public static String format(Date date, String pattern) {
        return getSdf(pattern).format(date);
    }

    public static Date parse(String dateStr, String pattern) throws ParseException {
        return getSdf(pattern).parse(dateStr);
    }

    public static String getMonthLastDate(String yyyyMM) {
        Date date = new Date();
        try {
            date = parse(yyyyMM, "yyyyMM");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar cale = Calendar.getInstance();
        cale.setTime(date);
        cale.add(Calendar.MONTH, 1);
        cale.set(Calendar.DAY_OF_MONTH, 0);
        String lastday = format(cale.getTime(), "yyyy-MM-dd");
        return lastday;
    }

    public static String add(String yyyyMMdd2, int year, int month, int day) {
        Date date = new Date();
        try {
            date = parse(yyyyMMdd2, "yyyy-MM-dd");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar cale = Calendar.getInstance();
        cale.setTime(date);
        cale.add(Calendar.YEAR, year);
        cale.add(Calendar.MONTH, month);
        cale.add(Calendar.DAY_OF_YEAR, day);
        String date2 = format(cale.getTime(), "yyyy-MM-dd");
        return date2;
    }

    /**
     * 得到几天前的时间
     * @param d
     * @param day
     * @return
     */
    public static String getDateBefore(Date d, int day) {
        Calendar cale = Calendar.getInstance();
        cale.setTime(d);
        cale.set(Calendar.DATE, cale.get(Calendar.DATE) - day);
        String date = format(cale.getTime(), "yyyy-MM-dd");
        return date;
    }

}
